import router from './router'
import store from './store'
import { asyncRoutes } from '@/router'
// import { Message } from 'element-ui'
import nprogress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

// 白名单数组
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  // 开启进度条
  nprogress.start()
  // 判断是否有token
  if (store.getters.token) {
    // 判断要跳转页面是否登录页面
    if (to.path === '/login') {
      // next()中写路径参数不会走后置路由守卫,所以要手动关进度条
      next('/')
      // 关闭进度条
      nprogress.done()
    } else {
      // 有token,但vuex中无用户数据,则发请求要数据
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        // 过滤数组
        const filterRoutes = asyncRoutes.filter(item => roles.menus.includes(item.name))
        // 修改vuex中的路由数组
        store.commit('user/chengeRoutesList', filterRoutes)
        // 给路由数组增加项
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      } else {
        next()
      }
      // next()
    }
  } else {
    // 判断是否白名单路径
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      // 关闭进度条
      nprogress.done()
    }
  }
})
// to	即将要进入的目标路由对象
// from	当前导航正要离开的路由
// next	回调方法
router.afterEach((to, from) => {
  // 关闭进度条
  nprogress.done()
})
